﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace DBService
{
	public partial class DlgEditUser : System.Windows.Forms.Form
	{
		public DlgEditUser(DlgServerManager main)
		{
			this.InitializeComponent();
			this.mainForm = main;
			this.mUser = main.currentUser;
			this.parent = this.mainForm.CurrentDepartment;
		}

		private void DlgAddDepartment_Load(object sender, EventArgs e)
		{
			this.txtRemark.Text = this.mUser.Remark;
			this.txtName.Text = this.mUser.Name;
			this.txtPassword.Text = this.mUser.Password;
			this.txtEmail.Text = this.mUser.Email;
			this.txtChineseName.Text = this.mUser.ChineseName;
			DbDepartment.FillDepartmentTree(BimServerDB.Default, this.tvDepart);
			this.tvDepart.ExpandAll();
			TreeNode selectedNode = this.testAllNode(this.tvDepart.Nodes, this.mUser.Department);
			this.tvDepart.SelectedNode = selectedNode;
			this.tvDepart.Select();
		}

		private TreeNode testAllNode(TreeNodeCollection nodes, DbDepartment department)
		{
			TreeNode result = null;
			if (department != null)
			{
				foreach (object obj in nodes)
				{
					TreeNode treeNode = (TreeNode)obj;
					if (treeNode.Text.Equals(department.Name))
					{
						result = treeNode;
						break;
					}
					result = this.testAllNode(treeNode.Nodes, department);
				}
			}
			return result;
		}

		private bool IsValidEmail(string strEmail)
		{
			return Regex.IsMatch(strEmail, "^[\\w\\.]+([-]\\w+)*@[A-Za-z0-9-_]+[\\.][A-Za-z0-9-_]");
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.txtName.Text.Trim() == "" || this.txtPassword.Text.Trim() == "")
				{
					MessageBox.Show("请填写用户名和密码。");
				}
				else
				{
					this.mUser.Name = this.txtName.Text.Trim();
					this.mUser.Email = this.txtEmail.Text.Trim();
					this.mUser.ChineseName = this.txtChineseName.Text.Trim();
					this.mUser.Remark = this.txtRemark.Text.Trim();
					if (this.pswChange)
					{
						this.mUser.Password = DbUser.ToMd5(this.txtPassword.Text.Trim());
					}
					this.mUser.ToDepartment((this.tvDepart.SelectedNode.Tag as DbDepartment).Id);
					this.mUser.UpdateToDb();
					base.DialogResult = DialogResult.OK;
					base.Close();
				}
			}
			catch (Exception)
			{
				this.txtName.Text = "";
				MessageBox.Show("修改发生异常,请检查是否有重名用户。");
			}
		}

		private void txtPassword_TextChanged(object sender, EventArgs e)
		{
			this.pswChange = true;
		}

		private DlgServerManager mainForm;

		private DbDepartment parent;

		private string mGroup = "FM";

		private DbUser mUser;

		private bool pswChange;
	}
}
